<template>
  <view class="list-page">
    <!-- 搜索栏 -->
    <view class="list-search-bar">
      <view class="list-search-input">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input
            v-model="searchKeyword"
            class="list-input"
            placeholder="搜索存储桶名称"
            @input="handleSearchInput"
            @confirm="handleSearch"
        />
        <uni-icons
            v-if="searchKeyword"
            type="clear"
            size="16"
            color="#999"
            @click="handleClear">
        </uni-icons>
      </view>
      <view class="list-filter-btn" @click="toggleFilter">
        <uni-icons type="filter" size="14" color="#666"></uni-icons>
        <text>筛选</text>
      </view>
    </view>

    <!-- 高级筛选抽屉 -->
    <uni-popup ref="filterPopup" type="right" :mask-click="false">
      <view class="list-filter-drawer">
        <view class="list-filter-header">
          <text class="list-filter-title">高级筛选</text>
          <uni-icons type="close" size="20" @click="closeFilter"></uni-icons>
        </view>

        <view class="list-filter-content">
          <view class="list-filter-item">
            <text class="list-filter-label">存储配置</text>
            <BottomSelect
                v-model="queryParams.configId"
                :options="storageOptions"
                value-field="configId"
                label-field="configName"
                placeholder="请选择存储配置"
                title="选择存储配置"/>
          </view>
        </view>

        <view class="list-filter-footer">
          <view class="btn btn-reset" @click="handleFilterReset">重置</view>
          <view class="btn btn-confirm" @click="handleFilterConfirm">确定</view>
        </view>
      </view>
    </uni-popup>

    <!-- 操作按钮栏 -->
    <view class="list-action-bar">
      <view class="btn btn-primary" @click="handleCreate" v-if="checkPermission(['file:bucket:add'])">
        <uni-icons type="plus" size="14" color="#007aff"></uni-icons>
        <text>创建桶</text>
      </view>
      <view class="btn btn-default" @click="handleRefresh">
        <uni-icons type="reload" size="14" color="#666"></uni-icons>
        <text>刷新</text>
      </view>
    </view>

    <!-- 存储桶列表 -->
    <view class="list-content">
      <view
          v-for="bucket in filteredBucketList"
          :key="bucket.bucketName"
          class="list-item"
          @click="handleView(bucket)">

        <view class="list-avatar">
          <view class="bucket-icon" :class="getBucketTypeClass()">
            <uni-icons type="folder" size="24" color="#fff"></uni-icons>
          </view>
        </view>

        <view class="list-info">
          <view class="list-header">
            <text class="list-title">{{ bucket.bucketName }}</text>
            <view v-if="bucket.isDefault" class="default-badge">
              默认
            </view>
            <view class="permission-badge" :class="getPermissionClass(bucket.permission)">
              {{ getPermissionText(bucket.permission) }}
            </view>
          </view>

          <view class="list-details">
            <view class="detail-item">
              <uni-icons type="cloud" size="14" color="#999"></uni-icons>
              <text class="detail-text">{{ getStorageTypeName(currentConfig?.storageType) }}</text>
            </view>

            <view class="detail-item" v-if="currentConfig?.configName">
              <uni-icons type="settings" size="14" color="#999"></uni-icons>
              <text class="detail-text">{{ currentConfig.configName }}</text>
            </view>

            <view class="detail-item" v-if="currentConfig?.endpoint">
              <uni-icons type="location" size="14" color="#999"></uni-icons>
              <text class="detail-text">{{ currentConfig.endpoint }}</text>
            </view>
          </view>
        </view>

        <view class="list-actions">
          <view class="action-btn action-primary" @click.stop="handleDetail(bucket)"
                v-if="checkPermission(['file:bucket:list'])">
            <uni-icons type="eye" size="14" color="#007aff"></uni-icons>
            <text class="action-text">详情</text>
          </view>
          <view
              class="action-btn action-warning"
              @click.stop="handlePermission(bucket)"
              v-if="currentConfig?.storageType !== 'local' && checkPermission(['file:bucket:edit'])">
            <uni-icons type="gear" size="14" color="#ff9500"></uni-icons>
            <text class="action-text">权限</text>
          </view>
          <view class="action-btn action-success" @click.stop="handleSetDefault(bucket)"
                v-if="checkPermission(['file:storage:edit'])">
            <uni-icons type="star" size="14" color="#34c759"></uni-icons>
            <text class="action-text">设为默认</text>
          </view>
          <view class="action-btn action-danger" @click.stop="handleDelete(bucket)"
                v-if="checkPermission(['file:bucket:remove'])">
            <uni-icons type="trash" size="14" color="#ff3b30"></uni-icons>
            <text class="action-text">删除</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="!loading && filteredBucketList.length === 0" class="list-empty">
      <uni-icons type="folder" size="48" color="#ddd"></uni-icons>
      <text class="list-empty-text">暂无存储桶数据</text>
      <button class="btn btn-primary" @click="handleCreate" v-if="checkPermission(['file:bucket:add'])">创建存储桶
      </button>
    </view>

    <!-- 创建存储桶对话框 -->
    <uni-popup ref="createPopup" type="center">
      <view class="create-modal">
        <view class="modal-header">
          <text class="modal-title">创建存储桶</text>
          <view class="modal-close" @click="closeCreate">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>

        <view class="modal-content">
          <view class="form-item">
            <text class="form-label">存储配置</text>
            <BottomSelect
                v-model="createForm.configId"
                :options="storageOptions"
                value-field="configId"
                label-field="configName"
                placeholder="请选择存储配置"
                title="选择存储配置"/>
          </view>

          <view class="form-item">
            <text class="form-label">桶名称</text>
            <uni-easyinput
                v-model="createForm.bucketName"
                :placeholder="getBucketNamePlaceholder()"
                :clearable="true">
            </uni-easyinput>
            <text class="form-tip">{{ getBucketNameTip() }}</text>
          </view>
        </view>

        <view class="modal-footer">
          <view class="btn btn-default" @click="closeCreate">取消</view>
          <view class="btn btn-primary" @click="submitCreate">确定</view>
        </view>
      </view>
    </uni-popup>

    <!-- 桶详情对话框 -->
    <uni-popup ref="detailPopup" type="center">
      <view class="detail-modal">
        <view class="modal-header">
          <text class="modal-title">存储桶详情</text>
          <view class="modal-close" @click="closeDetail">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>

        <view class="modal-content">
          <view class="detail-info">
            <view class="info-item">
              <text class="info-label">桶名称</text>
              <text class="info-value">{{ detailForm.bucketName }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">存储类型</text>
              <text class="info-value">{{ getStorageTypeName(currentConfig?.storageType) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">配置名称</text>
              <text class="info-value">{{ currentConfig?.configName }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">访问地址</text>
              <text class="info-value">{{ currentConfig?.endpoint }}</text>
            </view>
            <view class="info-item" v-if="currentConfig?.region">
              <text class="info-label">区域</text>
              <text class="info-value">{{ currentConfig.region }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">自定义域名</text>
              <text class="info-value">{{ currentConfig?.domain || '未配置' }}</text>
            </view>
          </view>
        </view>

        <view class="modal-footer">
          <view class="btn btn-default" @click="closeDetail">关闭</view>
        </view>
      </view>
    </uni-popup>

    <!-- 权限设置对话框 -->
    <uni-popup ref="permissionPopup" type="center">
      <view class="permission-modal">
        <view class="modal-header">
          <text class="modal-title">设置存储桶权限</text>
          <view class="modal-close" @click="closePermission">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>

        <view class="modal-content">
          <view class="form-item">
            <text class="form-label">桶名称</text>
            <uni-easyinput
                v-model="permissionForm.bucketName"
                :disabled="true">
            </uni-easyinput>
          </view>

          <view class="form-item">
            <text class="form-label">访问权限</text>
            <uni-data-checkbox
                v-model="permissionForm.permission"
                :localdata="permissionOptions"
                mode="single">
            </uni-data-checkbox>

            <view class="permission-tips">
              <view class="tip-item">
                <text class="tip-label">私有：</text>
                <text class="tip-text">只有桶拥有者可以访问</text>
              </view>
              <view class="tip-item">
                <text class="tip-label">公共读：</text>
                <text class="tip-text">任何人都可以读取桶中的文件</text>
              </view>
              <view class="tip-item">
                <text class="tip-label">公共读写：</text>
                <text class="tip-text">任何人都可以读取和写入桶中的文件</text>
              </view>
            </view>
          </view>
        </view>

        <view class="modal-footer">
          <view class="btn btn-default" @click="closePermission">取消</view>
          <view class="btn btn-primary" @click="submitPermission">确定</view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import {computed, getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {createBucket, deleteBucket, listBuckets, setBucketPermission} from '@/api/filemanager/bucket'
import {getStorageConfig, listStorageConfig, updateStorageConfig} from '@/api/filemanager/storage'
import {BottomSelect} from '@/components/select'
import {usePermission} from '@/utils/permission'

const {proxy} = getCurrentInstance()
const checkPermission = usePermission()

// 数据定义
const bucketList = ref([])
const storageOptions = ref([])
const currentConfig = ref(null)
const loading = ref(false)
const searchKeyword = ref('')
const filterPopup = ref(null)
const createPopup = ref(null)
const detailPopup = ref(null)
const permissionPopup = ref(null)

// 查询参数
const queryParams = reactive({
  configId: undefined
})

// 创建表单
const createForm = reactive({
  configId: undefined,
  bucketName: ''
})

// 详情表单
const detailForm = reactive({
  bucketName: ''
})

// 权限表单
const permissionForm = reactive({
  bucketName: '',
  permission: 'private'
})

// 权限选项
const permissionOptions = [
  {value: 'private', text: '私有'},
  {value: 'public-read', text: '公共读'},
  {value: 'public-read-write', text: '公共读写'}
]

// 过滤后的存储桶列表
const filteredBucketList = computed(() => {
  if (!searchKeyword.value) {
    return bucketList.value
  }
  return bucketList.value.filter(bucket =>
      bucket.bucketName.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 页面加载
onMounted(() => {
  loadStorageOptions()
})

// 加载存储配置选项
async function loadStorageOptions() {
  try {
    const response = await listStorageConfig({pageNum: 1, pageSize: 100})
    if (response.code === 200) {
      storageOptions.value = response.rows || []

      // 默认选择第一个配置
      if (storageOptions.value.length > 0) {
        const defaultConfig = storageOptions.value.find(item => item.isDefault === 1) || storageOptions.value[0]
        queryParams.configId = defaultConfig.configId
        currentConfig.value = defaultConfig
        createForm.configId = defaultConfig.configId
        getBucketList()
      }
    }
  } catch (error) {
    console.error('加载存储配置失败:', error)
  }
}

// 获取存储桶列表
async function getBucketList() {
  if (!queryParams.configId) {
    bucketList.value = []
    loading.value = false
    return
  }

  loading.value = true
  currentConfig.value = storageOptions.value.find(item => item.configId === queryParams.configId)

  try {
    const response = await listBuckets({configId: queryParams.configId})
    if (response.code === 200) {
      bucketList.value = response.data || []
    } else {
      proxy.$modal.showToast(response.msg || "获取存储桶列表失败")
      bucketList.value = []
    }
  } catch (error) {
    proxy.$modal.showToast("获取存储桶列表失败")
    bucketList.value = []
  } finally {
    loading.value = false
  }
}

// 获取存储类型名称
function getStorageTypeName(type) {
  const typeMap = {
    'local': '本地存储',
    'minio': 'MinIO',
    'aliyun': '阿里云OSS',
    'tencent': '腾讯云COS',
    'aws': 'AWS S3'
  }
  return typeMap[type] || type
}

// 获取存储桶类型样式类
function getBucketTypeClass() {
  return 'bucket-default'
}

// 获取权限样式类
function getPermissionClass(permission) {
  const classMap = {
    'private': 'permission-private',
    'public-read': 'permission-public-read',
    'public-read-write': 'permission-public-read-write'
  }
  return classMap[permission] || 'permission-default'
}

// 获取权限文本
function getPermissionText(permission) {
  const textMap = {
    'private': '私有',
    'public-read': '公共读',
    'public-read-write': '公共读写',
    'loading...': '加载中'
  }
  return textMap[permission] || '-'
}

// 获取桶名称占位符
function getBucketNamePlaceholder() {
  const selectedConfig = storageOptions.value.find(item => item.configId === createForm.configId)
  if (selectedConfig?.storageType === 'local') {
    return '请输入目录名称（如：images、documents）'
  }
  return '请输入存储桶名称（小写字母、数字、连字符）'
}

// 获取桶名称提示信息
function getBucketNameTip() {
  const selectedConfig = storageOptions.value.find(item => item.configId === createForm.configId)
  if (selectedConfig?.storageType === 'local') {
    return '目录名称用于组织文件，支持中文、英文、数字和常见符号'
  }
  return '桶名称必须全局唯一，只能包含小写字母、数字和连字符，长度3-63个字符'
}

// 事件处理
let searchTimer = null

function handleSearchInput() {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    // 搜索是在前端进行的，不需要重新请求
  }, 300)
}

function handleSearch() {
  // 搜索是在前端进行的
}

function handleClear() {
  searchKeyword.value = ''
}

function toggleFilter() {
  filterPopup.value.open()
}

function closeFilter() {
  filterPopup.value.close()
}

function handleFilterConfirm() {
  closeFilter()
  getBucketList()
}

function handleFilterReset() {
  if (storageOptions.value.length > 0) {
    const defaultConfig = storageOptions.value.find(item => item.isDefault === 1) || storageOptions.value[0]
    queryParams.configId = defaultConfig.configId
    currentConfig.value = defaultConfig
  }
  getBucketList()
}

// 业务操作方法
function handleCreate() {
  createForm.configId = queryParams.configId
  createForm.bucketName = ''
  createPopup.value.open()
}

function closeCreate() {
  createPopup.value.close()
}

async function submitCreate() {
  if (!createForm.configId) {
    proxy.$modal.showToast('请选择存储配置')
    return
  }
  if (!createForm.bucketName) {
    proxy.$modal.showToast('请输入桶名称')
    return
  }

  try {
    const response = await createBucket(createForm)
    if (response.code === 200) {
      proxy.$modal.showToast('创建成功')
      closeCreate()
      getBucketList()
    }
  } catch (error) {
    console.error('创建存储桶失败:', error)
  }
}

function handleDetail(bucket) {
  detailForm.bucketName = bucket.bucketName
  detailPopup.value.open()
}

function closeDetail() {
  detailPopup.value.close()
}

function handleView(bucket) {
  handleDetail(bucket)
}

function handlePermission(bucket) {
  permissionForm.bucketName = bucket.bucketName
  permissionForm.permission = bucket.permission || 'private'
  permissionPopup.value.open()
}

function closePermission() {
  permissionPopup.value.close()
}

async function submitPermission() {
  try {
    const response = await setBucketPermission({
      bucketName: permissionForm.bucketName,
      permission: permissionForm.permission,
      configId: queryParams.configId
    })
    if (response.code === 200) {
      proxy.$modal.showToast('权限设置成功')
      closePermission()
      getBucketList()
    }
  } catch (error) {
    console.error('设置权限失败:', error)
  }
}

async function handleSetDefault(bucket) {
  if (bucket.isDefault) {
    proxy.$modal.showToast('该桶已经是默认桶')
    return
  }

  try {
    await proxy.$modal.confirm(`是否确认将存储桶"${bucket.bucketName}"设置为当前存储配置的默认桶？`)

    // 先获取完整的存储配置信息
    const response = await getStorageConfig(queryParams.configId)
    const configData = response.data
    configData.bucketName = bucket.bucketName

    // 更新存储配置
    await updateStorageConfig(configData)
    proxy.$modal.showToast('设置默认桶成功')

    // 更新当前配置信息
    currentConfig.value.bucketName = bucket.bucketName
    // 重新获取桶列表以更新默认标识
    getBucketList()
  } catch (error) {
    console.error('设置默认桶失败:', error)
  }
}

async function handleDelete(bucket) {
  try {
    await proxy.$modal.confirm(`是否确认删除存储桶"${bucket.bucketName}"？`)

    const response = await deleteBucket({
      bucketName: bucket.bucketName,
      configId: queryParams.configId
    })
    if (response.code === 200) {
      proxy.$modal.showToast('删除成功')
      getBucketList()
    }
  } catch (error) {
    console.error('删除存储桶失败:', error)
  }
}

function handleRefresh() {
  getBucketList()
}
</script>

<style lang="scss" scoped>
@import '@/styles/list-page.scss';

// 存储桶图标样式
.bucket-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;

  &.bucket-default {
    background: linear-gradient(135deg, #667eea, #764ba2);
  }
}

// 默认标识
.default-badge {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

// 权限标识
.permission-badge {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;

  &.permission-private {
    background: #f0f0f0;
    color: #666;
  }

  &.permission-public-read {
    background: #f6ffed;
    color: #52c41a;
  }

  &.permission-public-read-write {
    background: #fff7e6;
    color: #fa8c16;
  }
}

// 模态框样式
.create-modal,
.detail-modal,
.permission-modal {
  width: 85vw;
  max-width: 500px;
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;

  .modal-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }

  .modal-close {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    border-radius: 50%;

    &:hover {
      background: #f5f5f5;
    }
  }
}

.modal-content {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;

  .btn {
    padding: 8px 16px;
    font-size: 14px;
    border-radius: 6px;
  }
}

// 表单样式
.form-item {
  margin-bottom: 20px;

  .form-label {
    display: block;
    margin-bottom: 8px;
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }

  .form-tip {
    display: block;
    margin-top: 4px;
    font-size: 12px;
    color: #999;
    line-height: 1.4;
  }
}

// 详情信息样式
.detail-info {
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }

    .info-label {
      font-size: 14px;
      color: #666;
      font-weight: 500;
    }

    .info-value {
      font-size: 14px;
      color: #333;
      text-align: right;
      flex: 1;
      margin-left: 12px;
    }
  }
}

// 权限提示样式
.permission-tips {
  margin-top: 12px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;

  .tip-item {
    display: flex;
    margin-bottom: 8px;
    font-size: 12px;
    line-height: 1.4;

    &:last-child {
      margin-bottom: 0;
    }

    .tip-label {
      color: #333;
      font-weight: 500;
      margin-right: 4px;
    }

    .tip-text {
      color: #666;
      flex: 1;
    }
  }
}
</style>
